<?php

namespace App\Repositories\Permission;

use App\Models\Admin;
use App\Repositories\BaseRepository;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Arr;

/**
 * 管理员仓储类
 * @method Admin|null getById(int $id): ?Admin
 * @method Admin|null create(array $attributes): ?Admin
 */
class AdminRepository extends BaseRepository
{
    public function __construct(Admin $model)
    {
        parent::__construct($model);
    }


    public function getByPhone(string $phone): ?Admin
    {
        return $this->model->query()->where('phone', $phone)->first();
    }

    public function paginate(array $params): LengthAwarePaginator
    {
        $query = $this->query();
        $keyword = Arr::get($params, 'keyword');
        if ($keyword) {
            $query->where('name', 'like', "%{$keyword}%")
                ->orWhere('phone', 'like', "%{$keyword}%");
        }

        $startDate = Arr::get($params, 'startDate');
        $endDate = Arr::get($params, 'endDate');

        if ($startDate && $endDate) {
            $query->where('created_at', '>=', $startDate);
            $query->where('created_at', '<=', $endDate);
        }

        return $query->orderBy('id')->paginate(10)->through(fn(Admin $admin) => [
            'id' => $admin->id,
            'name' => $admin->name,
            'phone' => $admin->phone,
            'role' => $admin->role ? $admin->role_name : '未知',
            'avatar' => $admin->avatar,
            'status' => $admin->status,
            'gender' => $admin->gender,
            'last_login_ip' => $admin->last_login_ip,
            'last_login_at' => $admin->last_login_at,
            'created_at' => $admin->created_at->format('Y-m-d'),
            'updated_at' => $admin->updated_at->format('Y-m-d'),
        ]);
    }

}
